'use strict';

module.exports = function(Hotel) {

  Hotel.getNearlyTen = function (lat, lng, cb) {
    var option = {
      where: {
        and: [
          {JD: {between: [lng - 0.03, lng + 0.03]}},
          {WD: {between: [lat - 0.03, lat + 0.03]}}
        ]
      }
    };
    var result = [];
    Hotel.find(option, function (err, data) {
      for(var i = 0; i < data.length; i++) {
        result.push({
          type: 'hotel',
          msg: data[i].NAME,
          addr: data[i].LG_DZ,
          lat: data[i].WD - 0,
          lng: data[i].JD - 0,
          distance: Math.floor(Math.abs(data[i].WD - lat) * 110000 
            + Math.abs(data[i].JD - lng) * 94000)
        })
      }
      cb(null, result);
    })
  };

  Hotel.remoteMethod(
    'getNearlyTen', {
      http: {path: '/getNearlyTen', verb: 'post'},
      accepts: [
        {arg: 'lat', type: 'number', required: 'true'},
        {arg: 'lng', type: 'number', required: 'true'}
      ],
      returns: {type: 'array', root: true}
    }
  );

  Hotel.searchData = function (searchText, lat, lng, cb) {
    var option = {
      where: {
        or: [
          {NAME: {like: '%' + searchText + '%'}},
          {LG_DZ: {like: '%' + searchText + '%'}}
        ]
      }
    };
    var result = [];
    Hotel.find(option, function (err, data) {
      for(var i = 0; i < data.length; i++) {
        result.push({
          type: 'hotel',
          msg: data[i].NAME,
          addr: data[i].LG_DZ,
          lat: data[i].WD - 0,
          lng: data[i].JD - 0,
          distance: Math.floor(Math.abs(data[i].WD - lat) * 110000 
            + Math.abs(data[i].JD - lng) * 94000)
        })
      }
      cb(null, result);
    })
  };

  Hotel.remoteMethod(
    'searchData', {
      http: {path: '/searchData', verb: 'post'},
      accepts: [
        {arg: 'searchText', type: 'string', required: 'true'},
        {arg: 'lat', type: 'number', required: 'true'},
        {arg: 'lng', type: 'number', required: 'true'}
      ],
      returns: {type: 'array', root: true}
    }
  );

};
